

// geo location
//
/*
var geo = Ext.create('Ext.util.Geolocation', {
    autoUpdate: true,
    listeners: {
        locationupdate: function(geo) {
           
        },
        locationerror: function(geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
            if(bTimeout){
                alert('GEO Timeout occurred.');
            } else {
                alert('GEO Error occurred.');
            }
        }
    }
});
*/

function playIt() {
    console.log('in playIt()');
}

// Populate the database 
//
function populateDB(tx) {
    // Drop tables
    tx.executeSql('DROP TABLE IF EXISTS DICTIONARYSOURCE');
    tx.executeSql('DROP TABLE IF EXISTS DICTIONARYTARGET');

    tx.executeSql('DROP TABLE IF EXISTS CONJUGATION');
    tx.executeSql('DROP TABLE IF EXISTS STEM');

    tx.executeSql('DROP TABLE IF EXISTS SPEAKER');
    tx.executeSql('DROP TABLE IF EXISTS COLLECTOR');
    
    // Create COLLECTOR table and populate
    tx.executeSql('CREATE TABLE IF NOT EXISTS COLLECTOR (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name, dateOfBirth, gender, comment)');
    tx.executeSql('INSERT INTO COLLECTOR (id, name, dateOfBirth, gender, comment) VALUES (1, "Bruce Birch", "1/1/1970", "Male", "first collector")');
    
    //CREATE SPEAKER table and populate
    tx.executeSql('CREATE TABLE IF NOT EXISTS SPEAKER (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name, dateOfBirth, gender, comment)');
    tx.executeSql('INSERT INTO SPEAKER (id, name, dateOfBirth, gender, comment) VALUES (1, "Axsoul Aden", "1/1/1970", "Male", "first speaker")');
    

    // **** MDM 13.06.2012 *** THIS TABLE STRUCTURE IS ABOUT TO CHANGE!!!
    // Create DICTIONARYTARGET table and populate
    tx.executeSql('CREATE TABLE IF NOT EXISTS DICTIONARYTARGET (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, speakerId, collectorId, targetWord, detailedEntry, audioURL, imageURL, note, savedDate, savedTime, geoLocation, recordingDevice, FOREIGN KEY (speakerId) REFERENCES SPEAKER(id), FOREIGN KEY (collectorId) REFERENCES COLLECTOR(id) )');
    tx.executeSql('INSERT INTO DICTIONARYTARGET (id, speakerId, collectorId, targetWord, detailedEntry, audioURL, imageURL, note) VALUES(1, 1, 1, "riwurrujun", "<p class=EntryParagraph><span class=Lexeme>&#8209;ara-</span><span class=fstandard><span lang=EN-US> </span></span><span class=Phoneticform>[a</span><span class=Phoneticform><span class=Phoneticform>a]</span><span lang=EN-US> <span class=Partofspeech>v.i.</span> <span class=Sensenumber>1)&nbsp;</span><span class=DefinitionE>go</span><span class=fstandard>.</span> <span class=Examplev>Ara.</span> <span class=ExamplefreetransE>They go, are going (e.g., walking along).</span> <span class=Examplev>Aju wara ba kujali.</span> <span class=ExamplefreetransE>The fire is going [i.e., burning, alight].</span> <span class=Examplev>Ijbara.</span> <span class=ExamplefreetransE>They go, are going (away).</span> <span class=Examplev>Ijbaran Warruwi ijuwuwani.</span> <span class=ExamplefreetransE>They went to Goulburn Island and are living over there.</span> <span class=Sensenumber>2)&nbsp;</span><span class=DefinitionE>come</span><span class=fstandard>.</span> <span class=Examplev>Ayuwara.</span> <span class=ExamplefreetransE>They come, are coming.</span> <span class=Examplev>Walmad awara.</span> <span class=ExamplefreetransE>Rain is coming.</span> <span class=Examplev>Abanara kuburr.</span> <span class=ExamplefreetransE>He\'s coming tomorrow.</span> <span class=Sensenumber>3)&nbsp;</span><span class=DefinitionE>be (of dynamic entity)</span><span class=fstandard>.</span> <span class=Examplev>jumung ngarang ngalduj</span> <span class=ExamplefreetransE>when I was little (lit. \'when I was going [around] little\')</span> <span class=Examplev>Wara ngalaldi balkbany birukurnaj, mana marndingunyuny, mana manbiri.</span> <span class=ExamplefreetransE>There is a smooth circle on the surface of the water where something has surfaced, maybe a dugong or a turtle.</span> <span class=Examplev>&quot;Nganduka warnjuj?&quot; &quot;Ijbaran wuka.&quot;</span><span class=ExamplefreetransE>\'Where\'s your sister?&quot; &quot;She went that way.&quot;</span> <span class=EncyclopedicinfoE>This stem is neutral with respect to direction of motion in relation to the speaker. With the non-directional series it means \'go along\', with the \'towards\' series it means \'come\', and with the \'away\' series it means \'go away\'. The third person plural form of the verb is used as a polite, or distancing form, when the speaker is in an avoidance relationship with the referent.</span></span></p>", "words/warnangkayin.m4a", "images/image1.jpg", "")');
    tx.executeSql('INSERT INTO DICTIONARYTARGET (id, speakerId, collectorId, targetWord, detailedEntry, audioURL, imageURL, note) VALUES(2, 1, 1, "balarrakan target detail data", "She is telling truth", "", "", "")');
    tx.executeSql('INSERT INTO DICTIONARYTARGET (id, speakerId, collectorId, targetWord, detailedEntry, audioURL, imageURL, note) VALUES(3, 1, 1, "balarrakan target detail data", "She is telling truth", "words/warnangkayin.m4a", "", "")');
    

    
    // Create DICTIONARYSOURCE table and populate
    tx.executeSql('CREATE TABLE IF NOT EXISTS DICTIONARYSOURCE (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable, FOREIGN KEY (dictionaryTargetId) REFERENCES DICTIONARYTARGET(id))');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (1, 1, "foot", "", "his/her/its foot", "on stomach", "balarrakanSource", "true")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (2, 1, "head", "n.", "his/her/its foot", "on stomach",  "riwurrujun", "true")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (3, 2, "hand", "n.", "his/her/its foot", "on stomach", "balarrakan", "true")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (4, 3, "hand1", "n.", "his/her/its foot", "on stomach", "balarrakan", "false")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (5, 2, "hand2", "n.", "his/her/its foot", "on stomach", "balarrakan", "false")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (6, 2, "hand3", "n.", "his/her/its foot", "on stomach", "balarrakan", "false")');
    tx.executeSql('INSERT INTO DICTIONARYSOURCE (id, dictionaryTargetId, sourceWord, partOfSpeech, inflection, disambiguation, targetWord, isEditable) VALUES (7, 2, "hand4", "n.", "his/her/its foot", "on stomach", "balarrakan", "false")');
    

    // Create STEM table and populate
    tx.executeSql('CREATE TABLE IF NOT EXISTS STEM (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, stem, inflectionType)');
    tx.executeSql('INSERT INTO STEM (id, stem, inflectionType) VALUES(0, "stem 0", 0 ) ');
    tx.executeSql('INSERT INTO STEM (id, stem, inflectionType) VALUES(1, "stem 1", 0 ) ');
    tx.executeSql('INSERT INTO STEM (id, stem, inflectionType) VALUES(2, "stem 2", 1 ) ');
    tx.executeSql('INSERT INTO STEM (id, stem, inflectionType) VALUES(3, "stem 3", 2 ) ');
    
    
    // Create CONJUGATION table and populate
    tx.executeSql('CREATE TABLE IF NOT EXISTS CONJUGATION (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL)');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(1, 4, 0, 0, 0, 0, 1, "source inflection 0", "target inflection 0", "orthography 0", "words/warnangkayin.m4a" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(2, 5, 0, 0, 0, 0, 2, "source inflection 1", "target inflection 1", "orthography 1", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(3, 4, 0, 0, 0, 0, 2, "source inflection 2", "target inflection 2", "orthography 2", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(4, 4, 1, 0, 0, 0, 1, "source inflection 3", "target inflection 3", "orthography 3", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(5, 1, 2, 0, 2, 1, 0, "source inflection 4", "target inflection 4", "orthography 4", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(6, 1, 2, 0, 1, 1, 0, "source inflection 5", "target inflection 5", "orthography 5", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(7, 1, 2, 0, 3, 1, 0, "source inflection 6", "target inflection 6", "orthography 6", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(8, 1, 2, 0, 3, 2, 0, "source inflection 7", "target inflection 7", "orthography 7", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(9, 1, 2, 0, 3, 3, 0, "source inflection 8", "target inflection 8", "orthography 8", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(10, 1, 3, 1, 3, 1, 0, "source inflection 9", "target inflection 9", "orthography 9", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(11, 1, 3, 2, 2, 2, 0, "source inflection 10", "target inflection 10", "orthography 10", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(12, 1, 3, 2, 2, 3, 0, "source inflection 11", "target inflection 11", "orthography 11", "" ) ');
    tx.executeSql('INSERT INTO CONJUGATION (id, subjectId, stemId, objectId, directionId, tenseId, numberId, sourceInflection, targetInflection, orthography, audioURL) VALUES(13, 1, 3, 2, 3, 3, 0, "source inflection 12", "target inflection 12", "orthography 12", "" ) ');

}





// Transaction error callback
//
function errorCB(err) {
    console.log("Error processing SQL: "+err.code);
}

// Transaction success callback
//
function successCB() {
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
}


// PhoneGap is ready
//
function onDeviceReady() {

    console.log('in onDeviceReady');
    var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
    db.transaction(populateDB, errorCB, successCB);
    
}


// Audio player
//
var my_media = null;
var mediaTimer = null;

// Generica Play audio function - Uses Phonegap Media object
//
function playAudio(src) {
	
    if (my_media == null) {
        // Create Media object from src
        my_media = new Media(src, onSuccess, onError);
        
    } // else play current audio
    // Play audio
    my_media.play();

    // Update my_media position every second
    if (mediaTimer == null) {
        mediaTimer = setInterval(function() {
            // get my_media position
            my_media.getCurrentPosition(
                // success callback
                function(position) {
                    if (position > -1) {
                        setAudioPosition((position) + " sec");
                    }
                },
                // error callback
                function(e) {
                    console.log("Error getting pos=" + e);
                    setAudioPosition("Error: " + e);
                }
            );
        }, 1000);
    }
}


// onSuccess Callback
//
function onSuccess() {
    console.log("playAudio():Audio Success");
}

// onError Callback 
//
function onError(error) {
    alert('code: '    + error.code    + '\n' + 
          'message: ' + error.message + '\n');
}


//<debug>
Ext.Loader.setPath({
    'Ext': 'sdk/src',
    'Sencha': 'app',
    'Sqlite': 'sqlite'
});
//</debug>

Ext.require('Sencha.util.InitSQLite');


Ext.apply(Ext.util.Format, {
	defaultDateFormat: 'd/m/Y'
});




Ext.application({
    // Rename this
    name: 'Sencha',

    // Global to store persistent file store so we don't have to create it every time.
    persistentFileStoreVar : "",
    mediaPtr : null,
                
    // Not sure if it is best practice to have all these here?
    controllers: ['DictionarySourceController', 'DictionaryDetailController', 'WordmakerController', 'TabBarController', 'InformationListController', 'PhraseListController'],

    views: ['DictionaryContainerList', 'DictionaryFormView', 'DictionarySourceListView', 'DictionarySourceNavigationView', 'DictionaryTargetDetailView', 'PhraseNavigationView', 'PhraseParentCategoryListView', 'PhraseChildCategoryListView', 'PhraseContainerList', 'PhraseListView', 'PhraseFormView', 'Wordmaker', 'TabView', 'SoundRecorder', 'DicMetadataFormView', 'CollectorFormView', 'SpeakerFormView', 'DictionaryDetailPageView', 'ImageView', 'InformationNavigationView', 'InformationListView', 'HowToUseAppInfoView', 'LanguageFootprintInfoView', 'SoundsOfIwaidjaInfoView', 'AboutThisAppInfoView', 'InformationContainerView' ],

    stores: ['DictionarySources', 'DictionaryTargets', 'PhraseCategories', 'PhrasesFiltered', 'Collectors', 'Speakers', 'Conjugations', 'Stems', 'DictionarySourcesFiltered'],
    models: ['DictionarySource', 'DictionaryTarget', 'PhraseCategory', 'Phrase', 'Collector', 'Speaker', 'Conjugation', 'Stem'],

    
    onReady: function() {
        //onDeviceReady();
    	Sencha.util.InitSQLite.initDb();
    },
    
    
    init: function() {
        
    },            
    
    launch: function() {
        // get persistent file store and store it for later use
        this.getPersistentFileStore();
                
        Ext.Viewport.add({
            xtype: 'tabview'
        });
        // hide splash screen (need to make sure autohide splash is set to false in info.plist)
        navigator.splashscreen.hide();
    },
    
    onUpdated: function() {
        Ext.Msg.confirm(
            "Application Update",
            "This application has just successfully been updated to the latest version. Reload now?",
            function() {
                window.location.reload();
            }
        );
    },

    // Explicity create getter and setter for persistentFileStoreVar. For some reason they aren't created automatically
    //
    setPersistentFileStoreVar: function(arg) {
        this.persistentFileStoreVar = arg;
    },

    getPersistentFileStoreVar: function() {
        return this.persistentFileStoreVar;
    },

    // Get persistent file store and store it in persistentFileStoreVal
    //
    getPersistentFileStore: function() {
        console.log("running getPersistentFileStore()");
        if ( !this.persistentFileStoreVar ) {
            console.log("getting getPersistentFileStoreVar...");
            window.requestFileSystem(
                LocalFileSystem.PERSISTENT, 
                0, 
                function(fsp) {
                    console.log ('fsp = ' + fsp.root.fullPath);
                    Sencha.app.setPersistentFileStoreVar(fsp.root.fullPath);
                },
                function(evt) {
                    console.log(evt.target.error.code);
                    var msg = 'An error occurred accessing persistent file store: ' + evt.target.error.code;
                    navigator.notification.alert(msg, null, 'Capture error');
                }
            );
        }
    }

    
});